<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人资料</h2>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form 
            :model="profileForm" 
            :rules="profileRules" 
            ref="profileFormRef" 
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/users/upload-avatar"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" disabled></el-input>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname"></el-input>
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone"></el-input>
            </el-form-item>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input type="textarea" v-model="profileForm.bio" :rows="4"></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="loading">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 修改密码 -->
        <el-tab-pane label="修改密码" name="password">
          <el-form 
            :model="passwordForm" 
            :rules="passwordRules" 
            ref="passwordFormRef" 
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="passwordForm.currentPassword" type="password" show-password></el-input>
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="passwordLoading">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 账号安全 -->
        <el-tab-pane label="账号安全" name="security">
          <div class="security-settings">
            <div class="security-item">
              <div class="security-info">
                <h3>登录设备管理</h3>
                <p>查看并管理您的登录设备</p>
              </div>
              <el-button>查看设备</el-button>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <h3>登录记录</h3>
                <p>查看您的账号登录历史</p>
              </div>
              <el-button>查看记录</el-button>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <h3>账号注销</h3>
                <p>永久删除您的账号和所有数据</p>
              </div>
              <el-button type="danger" @click="showDeleteAccountDialog = true">注销账号</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 账号注销确认对话框 -->
    <el-dialog
      v-model="showDeleteAccountDialog"
      title="账号注销确认"
      width="30%"
    >
      <div class="delete-account-warning">
        <el-alert
          title="此操作将永久删除您的账号和所有数据，且无法恢复！"
          type="error"
          :closable="false"
          show-icon
        />
        <p class="mt-4">请输入您的密码以确认注销账号：</p>
        <el-input 
          v-model="deleteAccountPassword" 
          type="password" 
          placeholder="请输入密码"
          show-password
        ></el-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteAccountDialog = false">取消</el-button>
          <el-button type="danger" @click="deleteAccount" :loading="deleteAccountLoading">
            确认注销
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const userStore = useUserStore()
const route = useRoute()
const activeTab = ref('basic')
const profileFormRef = ref()
const passwordFormRef = ref()
const loading = ref(false)
const passwordLoading = ref(false)
const showDeleteAccountDialog = ref(false)
const deleteAccountPassword = ref('')
const deleteAccountLoading = ref(false)

// 上传头像的请求头
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${userStore.token}`
  }
})

// 个人资料表单
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  bio: ''
})

// 修改密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 个人资料验证规则
const profileRules = {
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
onMounted(async () => {
  const userInfo = await userStore.fetchUserInfo()
  if (userInfo) {
    profileForm.username = userInfo.username || ''
    profileForm.nickname = userInfo.nickname || ''
    profileForm.email = userInfo.email || ''
    profileForm.phone = userInfo.phone || ''
    profileForm.avatar = userInfo.avatar || ''
    profileForm.bio = userInfo.bio || ''
  }
})

// 监听路由查询参数变化
watch(() => route.query.tab, (newTab) => {
  if (newTab === 'security') {
    activeTab.value = 'security'
  } else if (newTab === 'profile') {
    activeTab.value = 'basic'
  }
}, { immediate: true })

// 更新个人资料
const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      await userStore.updateUserInfo({
        nickname: profileForm.nickname,
        email: profileForm.email,
        phone: profileForm.phone,
        bio: profileForm.bio
      })
    } catch (error) {
      console.error('更新个人资料失败:', error)
    } finally {
      loading.value = false
    }
  })
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    passwordLoading.value = true
    
    try {
      await userStore.changePassword({
        currentPassword: passwordForm.currentPassword,
        newPassword: passwordForm.newPassword
      })
      
      // 清空表单
      passwordForm.currentPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      
      // 重置表单验证
      passwordFormRef.value.resetFields()
    } catch (error) {
      console.error('修改密码失败:', error)
    } finally {
      passwordLoading.value = false
    }
  })
}

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是JPG或PNG格式!')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  
  return true
}

// 头像上传成功的回调
const handleAvatarSuccess = (response: any) => {
  profileForm.avatar = response.url
  ElMessage.success('头像上传成功')
}

// 注销账号
const deleteAccount = async () => {
  if (!deleteAccountPassword.value) {
    ElMessage.error('请输入密码')
    return
  }
  
  try {
    deleteAccountLoading.value = true
    
    // 二次确认
    await ElMessageBox.confirm(
      '此操作将永久删除您的账号，是否继续？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用注销账号API
    await userStore.deleteAccount(deleteAccountPassword.value)
    
    // 跳转到首页
    window.location.href = '/'
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('注销账号失败:', error)
    }
  } finally {
    deleteAccountLoading.value = false
    showDeleteAccountDialog.value = false
    deleteAccountPassword.value = ''
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form,
.password-form {
  max-width: 500px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 50%;
}

.security-settings {
  padding: 10px 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.security-item:last-child {
  border-bottom: none;
}

.security-info h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: 500;
}

.security-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.delete-account-warning {
  margin-bottom: 20px;
}

.mt-4 {
  margin-top: 16px;
}
</style> 